/**
 * 判断是否为函数
 */
function isFunction(fn) {
  return !!fn && !fn.nodeName && fn.constructor != String
      && fn.constructor != RegExp && fn.constructor != Array
      && /function/i.test(fn + "");
}
/**
 * 判断是否为空
 */
function isNullOrEmpty(target) {
  var isNull = false;
  if (typeof (target) == 'undefined' || target == null || target == "" && target!= '0') {
    isNull = true;
  }
  return isNull;
}

/**
 * 判断目标对象是否为数字(空判断为非数)
 */
function isNum(target) {
  if (!isNaN(target) && !isNullOrEmpty(target) ) {
    return true;
  } else {
    return false;
  }
}

/**
 * 将数值转换为货币显示形式如10,111,555,999.55555
 * 
 */
function convertNumFormat(number) {
  number = number + "";
  if (isNullOrEmpty(number) || isNaN(number)) {
    return "";
  }
  var num = "";
  number = number.replace(/\,/g, "");
  var pre = false;
  var pointCount = number.split('.')[1];
  if (pointCount != null) {
    pointCount = "." + pointCount;
/*    for ( var i = pointCount.length - 1; i >= 0; i--) {
      if (pointCount.charAt(i) == "0")
        pointCount = pointCount.substr(0, i);
      else
        break;
    }*/
    if (pointCount == ".")
      pointCount = "";
  } else {
    pointCount = "";
  }

  if (isNaN(number) || number == "")
    return "";

  if (number < 0) {
    pre = true;
    number = Math.floor(Math.abs(number) - 0) + '';
  } else {
    number = Math.floor(number - 0) + '';
  }

  if (number.length <= 3)
    num = (number == '' ? '0' : number);
  else {
    var mod = number.length % 3;
    var output = (mod == 0 ? '' : (number.substring(0, mod)));
    for (i = 0; i < Math.floor(number.length / 3); i++) {
      if ((mod == 0) && (i == 0))
        output += number.substring(mod + 3 * i, mod + 3 * i + 3);
      else
        output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
    }
    num = output;
  }
  if (pre)
    num = "-" + num + pointCount;
  else
    num = num + pointCount;

  return num;
}
//文件下载功能,需要jquery
function downLoadFile(fileId){
	alert(fileId);
  
  if(typeof fileId == 'undefined' || fileId == null){
    alert("文件id出错。");
    return;
  }
  var ifameObj = $("<iframe/>");
  var src = getRootPath() + "/fileOper/getFile?attaId=" + fileId;
  
  $(document.body).append(ifameObj);
  ifameObj.attr("src",src);
  ifameObj.hide();
}

// num表示要四舍五入的数,v表示要保留的小数位数。
function decimal(num,v)
{
  if(!isNum(num) || num == ""){//非数时返回空
    num = "0.00";
  }
  if(!isNum(v)){
    v = 2;
  }
    var vv = Math.pow(10,v);
    var result = Math.round(num*vv)/vv;
    return result.toFixed(v);
}

/**
 * 一些常用的javascript函数(方法)
 * 
 * 为便于使用，均书写成String对象的方法 方法名 功 能 ———– ——————————– Trim 删除首位空格 Occurs 统计指定字符出现的次数
 * isDigit 检查是否由数字组成 isAlpha 检查是否由数字字母和下划线组成 isNumber 检查是否为数 lenb 返回字节数
 * isInChinese 检查是否包含汉字 isEmail 简单的email检查 isDate 简单的日期检查，成功返回日期对象 isInList
 * 检查是否有列表中的字符字符 isInList 检查是否有列表中的字符字符
 */

/** * 检查是否有列表中的字符字符 ** */
/** * 删除首尾空格 ** */
String.prototype.Trim = function() {
return this.replace(/(^\s*)|(\s*$)/g, "");
};
/** * 统计指定字符出现的次数 ** */
String.prototype.Occurs = function(ch) {
// var re = eval("/[^"+ch+"]/g");
// return this.replace(re, "").length;
return this.split(ch).length-1;
};
/** * 检查是否由数字组成 ** */
String.prototype.isDigit = function() {
var s = this.Trim();
return (s.replace(/\d/g, "").length == 0);
};
/** * 检查是否由数字字母和下划线组成 ** */
String.prototype.isAlpha = function() {
return (this.replace(/\w/g, "").length == 0);
};
/** * 检查是否为数 ** */
String.prototype.isNumber = function() {
var s = this.Trim();
return (s.search(/^[+-]?[0-9.]*$/) >= 0);
};
/** * 返回字节数 ** */
String.prototype.lenb = function() {
return this.replace(/[^\x00-\xff]/g,"**").length;
};
/** * 检查是否包含汉字 ** */
String.prototype.isInChinese = function() {
return (this.length != this.replace(/[^\x00-\xff]/g,"**").length);
};
/** * 简单的email检查 ** */
String.prototype.isEmail = function() {
var strr;
var mail = this;
var re = /(\w+@\w+\.\w+)(\.{0,1}\w*)(\.{0,1}\w*)/i;
re.exec(mail);
if(RegExp.$3!="" && RegExp.$3!="." && RegExp.$2!=".")
strr = RegExp.$1+RegExp.$2+RegExp.$3;
else
if(RegExp.$2!="" && RegExp.$2!=".")
strr = RegExp.$1+RegExp.$2;
else
strr = RegExp.$1;
return (strr==mail);
};

String.prototype.isInList = function(list) {
var re = eval("/["+list+"]/");
return re.test(this);
};
// / <summary>
// / 只能是数字
// / </summary>
// / <returns>如果是数字与字母，返回真，否则返回假</returns>
String.prototype.IsDigit = function()
{
var reg = /^\d+$/g;
return reg.test(this);
};
// / <summary>
// / 只能是数字和字母
// / </summary>
// / <returns>如果是数字与字母，返回真，否则返回假</returns>
String.prototype.IsAlphaDigit = function()
{
var reg = /^[a-zA-Z0-9]+$/g;
return reg.test(this);
};
// / <summary>
// / 只能是数字、字母与下划线
// / </summary>
// / <returns>如果是数字、字母与下划线，返回真，否则返回假</returns>
String.prototype.IsAlpha = function()
{
var reg = /^\w+$/g;
return reg.test(this);
};

/** * 简单的日期检查，成功返回日期对象 */
String.prototype.isDate = function() {
var p;
//日期格式为YYYY-MM-DD
var re1 =/^((((1[6-9]|[2-9]d)d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]d|3[01]))|(((1[6-9]|[2-9]d)d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]d|30))|(((1[6-9]|[2-9]d)d{2})-0?2-(0?[1-9]|1d|2[0-8]))|(((1[6-9]|[2-9]d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/;

if(re1.test(this)) {
  p = re1.exec(this);
  return new Date(p[1],p[2],p[3]);
}
return false;
}
// 转换成两位小数,将数值转换为货币显示形式
function numFormate(value){
  var num = value * 1.0;
  num = num.toFixed(2);
  if (isNaN(num)) {
    num = "0.00";
  }
  if(isNullOrEmpty(num)){
    return ""; 
  }
  num += "";
  var currence="";
  var intLen="";
  // 取得整数部分的长度
  for(var i=0;i<num.length;i++){
    if(num.charAt(i)=="."){
      intLen=i;
      break;
    }else{
      intLen=num.length;
    }
  }
  for(var i=0;i<num.length;i++){
    currence+=num.charAt(i);
    if(num.charAt(i)=="."){
      if(currence.charAt(currence.length-2)==","){
        currence=currence.substr(0,currence.length-2);
        currence+=".";
      }
      currence+=num.substr(i+1);
      break;
    }
    if((i+1+(3-intLen%3))%3==0){
      currence+=",";
    }
  }
  if(intLen==num.length){
    currence=currence.substr(0,currence.length-1);
  }
  return currence;
}

//js获取项目根路径，如： http://localhost:8083/uimcardprj
function getRootPath(){
  //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
  var curWwwPath=window.document.location.href;
  //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
  var pathName=window.document.location.pathname;
  var pos=curWwwPath.indexOf(pathName);
  //获取主机地址，如： http://localhost:8083
  var localhostPaht=curWwwPath.substring(0,pos);
  //获取带"/"的项目名，如：/uimcardprj
  var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
  return(localhostPaht+projectName);
}

/**
 * 显示审批意见
 * @param paramter.bussinessId
 * @param paramter.processId
 * @param paramter.divId
 */
function showReviewInfo(paramter){
  var postUrl = getRootPath() + "/workFlow/getReviewInfos";
  var param = {};
  if(!isNullOrEmpty(paramter.bussinessId)){
    param.bussinessId = paramter.bussinessId;
  }
  if(!isNullOrEmpty(paramter.processId)){
    param.processId = paramter.processId ;
  }
  
  var divId = "approvalInfos";
  if(!isNullOrEmpty(paramter.divId)){
    divId = paramter.divId ;
  }
  $.post(postUrl,param,function(data){
         if($.isArray(data) && data.length > 0)
         {
           $("#" + divId).show();
           $("#" + divId).empty();
           var spaceTable = $('<table id="approvalInfosSpan"><tr><td height="2"></td></tr></table>');
           var infoTable = $('<table id="approvalInfos" width="100%" cellpadding="1" cellspacing="0"></table>');
           var head = '<tr><td colspan="6" class="t_sld l_sld b_sld r_sld dispHeader"><table cellpadding="2" cellspacing="2"><tr>'
               + '<td class="dispHeader">'+approvalInfoOld+'</td></tr></table></td></tr>';
           infoTable.append(head);
           $("#" + divId).append(spaceTable);
           
           $.each(data,function(i,info){
             var tr =  $("<tr>");
             tr.append("<td class='dispL l_sld b_sld' align='right' width='10%'>"+approvalPerson+"</td>");
             tr.append("<td  class='dispL l_sld b_sld' align='left' width='23%'>"+info.personName+"&nbsp;</td>");
             tr.append("<td class='dispL l_sld b_sld' align='right' width='10%'>"+approvalResult+"</td>");
             tr.append("<td  class='dispL l_sld b_sld' align='left' width='23%'>"+info.outCome+"&nbsp;</td>");
             tr.append("<td class='dispL l_sld b_sld' align='right' width='10%'>"+approvalDate+"</td>");
             tr.append("<td  class='dispL l_sld r_sld b_sld' align='left' width='24%'>"+ info.end+"&nbsp;</td>");
             infoTable.append(tr);
             
             tr =  $("<tr>");
             tr.append("<td class='dispL l_sld b_sld' align='right'>"+approvalInfo+"</td>");
             tr.append("<td  class='dispC l_sld b_sld r_sld' align='left' colspan='5'><span>"+ info.approvalViews+"&nbsp;</span></td>");
             infoTable.append(tr);
             
             if(info.attachments){
               var attachments = info.attachments;
               var attachmentsHtml = "";
               var attachment = {};
               for(var i = 0; i < attachments.length; i++){
                 attachment = attachments[i];
                 attachmentsHtml = attachmentsHtml + '<div>'+
                 '<a href=\'javascript:downLoadFile("'+attachment.attaId+'")\'>' + attachment.attaName +'</a>&nbsp;</div>';
               };
               tr =  $("<tr>");
               tr.append("<td class='dispL l_sld b_sld' align='right'>"+atta+"</td>");
               tr.append("<td  class='dispC l_sld b_sld r_sld' align='left' colspan='5'>"
                   +attachmentsHtml +"</td>");
                 infoTable.append(tr);
             }
          });
          $("#" + divId).append(infoTable);
         }
       });
}
/**
 * 打开流程实例状态图
 * processId:流程实例id
 * openStatus:流程实例窗口状态信息,可以为空
 */
function showWFProcess(processId,openStatus){
    var tempOpenStatus = "dialogWidth=600px;dialogHeight=600px;scroll:no;status:no;help:no";
    if(!isNullOrEmpty(openStatus)){
      tempOpenStatus = openStatus;
    }
    window.showModalDialog(getRootPath() +"/workFlow/showPic?processId=" + processId, {}, tempOpenStatus);
}

/**
 * 通过任务id获取任务详细信息
 * @param taskId
 * @returns
 */
function getTaskInfo(taskId,processInstanceId){
  var taskInfo = null;
  var param = {};
  if(typeof taskId != 'undefined' && taskId != ''){
	  param.taskId = taskId;
  }
  if(typeof processInstanceId != 'undefined' && processInstanceId != ''){
	  param.processInstanceId = processInstanceId;
  }
  
  $.ajax({
        async:false,
        cache:false,
        data:param,
        url:getRootPath() + "/workFlow/getTaskInfo",
        success:function(data){
          if(typeof data.id != 'undefined'){
            taskInfo = data;
          }
          
           }
  });
  return taskInfo;
  
}

/**
 * 执行同步ajax请求
 * @param relativeUrl url地址 如:/workFlow/getTaskInfo
 * @param param 请求参数 json格式
 * 
 * @returns 请求后返回值
 */
function getSyncData(relativeUrl,param){
    var result = "";
      $.ajax({
        async:false,
        cache:false,
        data:param,
        url:getRootPath() + relativeUrl,
        success:function(data){
          result = data;
          }
      });
      
      return result;
  }

/**
 * 文件上传控件初始化,
 * 
 * @param fileId 文件输入框id
 * @param fileQueueId 文件名显示div id
 * @param fileInfo json类型文件信息,与uploadify控件属性相同,增加了completeFunction属性,在
 * 
 */

function initFileComponent(fileId,fileQueueId,fileInfo){
  var _fileNames = "";
  var _filePaths = "";
  var rootPath = getRootPath();
  var defaultSize = 2097152;
  if(typeof fileInfo.sizeLimit != 'undefined'){
    defaultSize = fileInfo.sizeLimit;
  }
  var defaultFileInfo = {
          'uploader'  : rootPath + "/scripts/xinma/uploadify.swf",
          'script'    : rootPath + '/common/doUpload.jsp',
          'cancelImg' : rootPath + '/scripts/xinma/cancel.png',
          'folder'    : rootPath + '/uploads',
          'fileExt'     : null,
          'fileDesc'    : '上传文件',
          'sizeLimit'   : defaultSize,
          'auto'      : false,
          'queueID': fileQueueId,
          'multi':true,
          'buttonText':'',
          'buttonImg':rootPath +'/images/desc.gif',
          'width':50,
          'height': 18,
          'onComplete'  : function(event, ID, fileObj, response, data) {
              var fileName=response.replace(/(\n[\s|\t]*\r*\n)/g, '\n');
              var filePath=fileObj.filePath;
              //返回的文件名称取得换行，空格
              var str1=response.replace(/(\n[\s|\t]*\r*\n)/g, '\n');
              var str2=str1.replace(/^[\n|\r\n]*|[\n|\r\n]*$/g,'');
              if (_fileNames == "") {
                _fileNames = str2;
                } else {
                  _fileNames = _fileNames + "," + str2;
                }
              if (_filePaths == "") {
                _filePaths = filePath;
              } else {
                _filePaths = _filePaths + "," + filePath;
              }
          },
          'onError' : function(event, ID, fileObj, errorObj) {
              if(errorObj.type=="File Size"){
                var infoOpt = {msg:"上传文件不能超过"+getFileSize(defaultSize)+"!",title:"提示"};
                  $.messager.show(infoOpt);
                 //删除超过大小的文件
                 $("#" + fileId).uploadifyCancel(ID.replace("file_upload",""));
               }
            },
          'onAllComplete' : function(event, data) {
          var fileObj = {};
          fileObj.fileNames = _fileNames;
          fileObj.filePaths = _filePaths;
            $("#" + fileQueueId).text("");
            if($.isFunction(fileInfo.completeFunction)){
              fileInfo.completeFunction.call(this,fileObj);
            }
          }
  };
  //替换默认数据
  for(var name in fileInfo){
    defaultFileInfo[name] = fileInfo[name];
  }
  
  /*上传控件初始化*/
  $('#' + fileId).uploadify(defaultFileInfo);
}

function fileComponentUpload(fileId){
   $('#' + fileId).uploadifyUpload();
}

function getFileSize(fileByte){
  var formateSize = "";
  formateSize = fileByte/1024/1024;
  
  return numFormate(formateSize) + "M";
}

// 验证单据是否可以进行预付款
function checkPayApply(query) {
  var flag = false;
  $.ajax({
    async:false,
    cache:false,
    data:query,
    url:getRootPath() + "/traPayApply/canAddPayApply",
    success:function(data){
      if (data != null) {
        if ("1"==data.flag) {
          flag = true;
        }
      }
    }
  });
  return flag;
}

/**
 * 预付款时验证发票是否已经审批通过
 */
function validateTraInvoice(oriDocId) {
  var flag = false;
  var query = {};
  query.oriDocId = oriDocId;
  $.ajax({
    async:false,
    cache:false,
    data:query,
    url:getRootPath() + "/traInvoice/validateTraInvoice",
    success:function(data){
      if (data != null) {
        if ("-1"==data.message) {
          flag = true;
        }
      }
    }
  });
  return flag;
}

/**
 * 验证付款申请单是否已经审批通过
 */
function validatePayApplyStatus(query) {
  var flag = false;
  $.ajax({
    async:false,
    cache:false,
    data:query,
    url:getRootPath() + "/traInvoice/validatePayApplyStatus",
    success:function(data){
      if (data != null) {
        flag = data.message;
      }
    }
  });
  return flag;
}
